package com.cgnpc.framework.userinfo;


import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.client.RestClient;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.config.Constants;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.vo.CgnRequestHeader;
import com.cgnpc.cud.boot.autoconfigure.aep.AepProperties;
import com.cgnpc.cud.core.common.util.StringUtils;
import com.cgnpc.cud.shiro.util.ContextHolder;
import com.cgnpc.framework.utils.CgnHeader;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.cgnpc.cud.shiro.util.ContextHolder;

/******************************
 * 用途说明:  获取当前用户
 * 作者姓名: pxmwrya
 * 创建时间: 2019/6/19_8:54
 ******************************/
@Service
public class CurrentUser {

    @Autowired
    RestClient restClient;

    @Autowired
    AepProperties aepProperties;

    private String devMode;

    @Value("${spring.profiles.usemock}")
    private void setDevMode(String dm) {
        devMode = dm;
    }

    //保存人员信息  建议保存到redis
    private final static Map usersMap = new HashMap<>();

    /**********************************
     * 用途说明:获取用户ID  pxmwrya
     * 参数说明
     * 返回值说明:  pxmwrya
     ***********************************/
    public static String getUser(){
//        if("local".equals(devMode)) {
//            return "P622400";
//        }
        String userId = ContextHolder.getPrincipalName();

        return userId;
    }

    /**********************************
     * 用途说明:获取用户姓名  阮洋
     * 参数说明
     * 返回值说明: 阮洋
     ***********************************/
    public static String getUserRealName(){
//        if("local".equals(devMode)) {
//            return "潘瑞辉";
//        }
        Map userHashMap = (HashMap)usersMap.get(getUser());
        String userInfo = userHashMap.get("userName").toString();
        return userInfo.substring(userInfo.indexOf("]")+1);
    }

    /**********************************
     * 用途说明:获取当前用户姓名 [pxmwrya]阮洋
     * 参数说明
     * 返回值说明: [pxmwrya]阮洋
     ***********************************/
    public  String getNowUser(){
        String userId = getUser();
        String userName = getUserInfo(userId);
        if (StringUtils.isEmpty(userName)){
            return userId;
        }
        return userName;
    }

    /**********************************
     * 用途说明: 获取人员信息
     * 参数说明 userId
     * 返回值说明:
     ***********************************/
    public static Map getUsersInfo(String userId){
        Map userHashMap = (HashMap)usersMap.get(userId);
        return userHashMap;
    }

    /**********************************
     * 用途说明: 从中台获取人员信息
     * 参数说明
     * 返回值说明:
     ***********************************/
    public UserInfo getCurrentUserDetail(){
        String user = getUser();
        getUserInfo(user);
        Map userHashMap = (HashMap)usersMap.get(user);
        String s = JacksonUtil.writeValueAsString(userHashMap);
        UserInfo userInfo = JacksonUtil.readValue(s, UserInfo.class);
        return userInfo;
    }

    /**********************************
     * 用途说明: 获取用户姓名   阮洋
     * 参数说明 userId
     * 返回值说明:
     ***********************************/
    public String getUserName(String userId){
        if(usersMap.get(userId) != null){
            Map map = (Map) usersMap.get(userId);
            String userInfo = map.get("userName").toString();
            return userInfo.substring(userInfo.indexOf("]")+1);

        }else{
            String userInfo = getUserInfo(userId);//[PXMWRYA]阮洋
            return userInfo.substring(userInfo.indexOf("]")+1);
        }
    }

    /**********************************
     * 用途说明: 调用中台人员服务  usercenter
     * 参数说明 userId
     * 返回值说明:
     {
     "responseId": "1",
     "code": "200",
     "msg": "成功",
     "data": [{
     "userStatus": "正常",
     "deptCodePath": "CNOC\\CPC",
     "remark": "",
     "userNamePy": "XU GUANG MING",
     "userDeptId": "608262",
     "contactAddr": "广东省深圳市新浩壹都(A座3818)",
     "state": "广东省深圳市",
     "email": "P910230@gnpjvc.com.cn",
     "userSex": "男",
     "creator": "Adminastrator",
     "userShortPy": "XGM",
     "deptNamePath": "运营公司\\党群工作部（党委办公室）",
     "userDept": "党群工作部（党委办公室）",
     "cellphoneNo": "无手机号信息",
     "userDeptNo": "CPC",
     "updateTime": "2018-05-01 00:00:00",
     "userName": "[P910230]徐光明",
     "userNameEng": "XU GUANG MING",
     "userId": "P910230",
     "telephoneNo": "",
     "createTime": "2018-05-01 00:00:00",
     "deptIdPath": "603115\\608262",
     "postCode": "",
     "updatePerson": "Adminastrator"
     }]
     }
     ***********************************/
    public String getUserInfo(String userId){
        if("local".equals(devMode)) {
            Map userMap = JacksonUtil.readValue("{\n" +
                    "        \"userStatus\": \"正常\",\n" +
                    "        \"deptCodePath\": \"CNPEC\\\\SUE\\\\SMB\",\n" +
                    "        \"remark\": \"\",\n" +
                    "        \"userNamePy\": \"PAN RUI HUI\",\n" +
                    "        \"userDeptId\": \"601420\",\n" +
                    "        \"contactAddr\": \"nullnullnull(null)\",\n" +
                    "        \"state\": \"nullnull\",\n" +
                    "        \"email\": \"P622400@gnpjvc.com.cn\",\n" +
                    "        \"userSex\": \"男\",\n" +
                    "        \"creator\": \"Adminastrator\",\n" +
                    "        \"userShortPy\": \"PRH\",\n" +
                    "        \"deptNamePath\": \"中广核工程有限公司\\\\调试中心\\\\项目控制分部\",\n" +
                    "        \"userDept\": \"项目控制分部\",\n" +
                    "        \"cellphoneNo\": \"无手机号信息\",\n" +
                    "        \"userDeptNo\": \"SMB\",\n" +
                    "        \"updateTime\": \"2018-05-01 00:00:00\",\n" +
                    "        \"userName\": \"[P622400]潘瑞辉\",\n" +
                    "        \"userNameEng\": \"PAN RUI HUI\",\n" +
                    "        \"userId\": \"P622400\",\n" +
                    "        \"telephoneNo\": \"\",\n" +
                    "        \"createTime\": \"2018-05-01 00:00:00\",\n" +
                    "        \"deptIdPath\": \"4700\\\\4726\\\\601420\",\n" +
                    "        \"postCode\": \"\",\n" +
                    "        \"updatePerson\": \"Adminastrator\"\n" +
                    "    }", HashMap.class);
            String userInfo = userMap.get("userName").toString();
            usersMap.put(userId,userMap);
            return userInfo;
        }
        //调用中台人员服务
        String userInfo = "";
        String realServiceUrl = Constants.USERCENTER_URL + "/getUserInfoByUserId";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        try{
            header = CgnHeader.getHeader(realServiceUrl,aepProperties);
            url = url+"?userId="+userId;
            //调用远程接口
            result = restClient.postCgnVoForRest(url,header,null);
            if(result.getCode().equals("200")){
                ArrayList list = (ArrayList) result.getData();
                if(list != null && list.size() > 0){
                    Map userMap = (HashMap)list.get(0);
                    userInfo = userMap.get("userName").toString();
                    //保存数据信息
                    usersMap.put(userId,userMap);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return userInfo;
    }

    /**********************************
     * 用途说明: 调用中台人员服务 获取多用户的信息
     * 参数说明 userIds 逗号分割  p123456,p234567
     * 返回值说明:
     ***********************************/
    public List getUsersByUserCenter(String userIds){
        //调用中台人员服务
        List usersInfo = new ArrayList<>();
        String realServiceUrl = Constants.USERCENTER_URL + "/getStaffsByStaffNos";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;

        try{
            header = CgnHeader.getHeader(realServiceUrl,aepProperties);
            url = url+"?staffNos="+userIds;
            //调用远程接口
            result = restClient.postCgnVoForRest(url,header,null);
            if(result.getCode().equals("200")){
                ArrayList list = (ArrayList) result.getData();
                usersInfo.addAll(list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return usersInfo;
    }


    /**********************************

     * 用途说明: 调用中台人员服务 由员工号获取员工工作部门直属领导 20210902

     * 返回值说明:
     ***********************************/
    public List getUsersByBoss(String userIds){
        //调用中台人员服务
        List usersInfo = new ArrayList<>();
        //String realServiceUrl = Constants.USERCENTER_URL + "/getHeaderInDeptByStaffNo";
       // String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        //String realServiceUrl = Constants.API_GATEWAY_URL_T + "/hrcenter/getHeaderInWorkDeptByStaffNo";
		String realServiceUrl = Constants.USERCENTER_URL+"/getHeaderInWorkDeptByStaffNo";
		//System.out.println("---270-Constants.USERCENTER_URL"+Constants.USERCENTER_URL);
        String url = realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        try{
            header = CgnHeader.getHeader(realServiceUrl,aepProperties);
            //System.out.println("---276-header"+header);
            url = url+"?staffNo="+userIds;
            //System.out.println("---277-url"+url);
            //调用远程接口
            result = restClient.postCgnVoForRest(url,header,null);
            if(result.getCode().equals("200")){
                ArrayList list = (ArrayList) result.getData();
                usersInfo.addAll(list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return usersInfo;
    }

//    public List getUsersByRole(String userId){
//        //调用中台人员服务
//        List usersInfo = new ArrayList<>();
//        //String realServiceUrl = Constants.USERCENTER_URL + "/getHeaderInDeptByStaffNo";
//        // String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
//        //String realServiceUrl = Constants.API_GATEWAY_URL_T + "/hrcenter/getHeaderInWorkDeptByStaffNo";
//        String realServiceUrl = "/uauauth/role/getRoleByLoginNameAndAppCode?loginName="+userId+"&appCode=SCP";
//        String url = realServiceUrl;
//
//        CgnRequestHeader header = null;
//        ApiResult result = null;
//        try{
//            header = CgnHeader.getHeader(realServiceUrl,aepProperties);
//            System.out.println("---303-header"+header);
//            System.out.println("---305-url"+url);
//            //调用远程接口
//            result = restClient.postCgnVoForRest(url,header,null);
//            if(result.getCode().equals("200")){
//                ArrayList list = (ArrayList) result.getData();
//                usersInfo.addAll(list);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return usersInfo;
//    }

}